// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-15

package list

import (
	"context"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/kind"
	"server/app/lib"
)

// Logic
// 加载用户资料.
type Logic struct {
	arcade   *models.Arcades
	request  *Request
	response []*Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: make([]*Response, 0),
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Query(i, o.request); err == nil {
		o.arcade, _ = lib.Arcade.GetMaster().GetArcade(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err    error
		filter = map[string]any{
			"arcade_id": o.arcade.Id,
			"date":      o.request.Date,
			"type":      o.request.Type,
		}
		list       []*models.ArcadeFinance
		listUserId = make([]kind.UserId, 0)
		res        = result.New()
		service    = services.NewArcadeFinanceService()
		total      int64
	)

	// 1. 分页列表.
	if list, total, err = service.Paging(ctx, filter, o.request.Page, o.request.Size); err != nil {
		return res.WithError(errs.ErrDatabaseQuery)
	}

	// 2. 遍历列表
	for _, item := range list {
		// 2.1 用户列表.
		if item.UserId.IsBound() {
			listUserId = append(listUserId, item.UserId)
		}

		// 2. 加入结果.
		o.response = append(o.response,
			(&Response{}).With(item),
		)
	}

	// 3. 用户列表.
	if len(listUserId) > 0 {
		var mapper map[kind.UserId]*models.Users
		if mapper, err = services.NewUsersService().MapByIdList(ctx, listUserId); err != nil {
			return res.WithError(err)
		}
		for _, v := range o.response {
			if v.UserId.IsBound() {
				if u, ok := mapper[v.UserId]; ok {
					v.WithUser(u)
				}
			}
		}
	}

	// 4. 分页结果.
	return res.WithPaging(o.response, total, o.request.Page, o.request.Size)
}
